<template>
  <div
    :class="className"
    :style="{height: height, width: width}"
  />
</template>

<script lang="ts">
import * as echarts from 'echarts'
import { EChartsOption } from 'echarts'
import { Component, Prop, Watch } from 'vue-property-decorator'
import { mixins } from 'vue-class-component'
import ResizeMixin from '@/components/Charts/mixins/resize'
import { ScoreModelAndData } from '@/api-scp/types'

@Component({
  name: 'ScoresRadarChart',
  components: {}
})
export default class extends mixins(ResizeMixin) {
  @Prop({ default: 'chart' }) private className!: string
  @Prop({ default: '100%' }) private width!: string
  @Prop({ default: '500px' }) private height!: string
  @Prop({ required: true }) private modelAndData!: ScoreModelAndData

  @Watch('modelAndData', { deep: true })
  private onModelAndDataChange(value: ScoreModelAndData) {
    this.setOptions(value)
  }

  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
  }

  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  }

  private async initChart() {
    this.chart = echarts.init(this.$el as HTMLDivElement)

    this.setOptions(this.modelAndData)
  }

  private setOptions(modelAndData: ScoreModelAndData) {
    if (!this.chart) {
      return
    }

    const {
      model,
      data
    } = modelAndData

    const indicator = model.items.map(({
      name,
      max
    }) => {
      return {
        name,
        max
      }
    })

    const chartData = data.map(({
      name,
      seriesDataObj
    }) => {
      const seriesData = model.items.map(item => seriesDataObj[item.field])
      return {
        value: seriesData,
        name
      }
    })

    const option: EChartsOption = {
      legend: {
        bottom: 0
      },
      tooltip: { },
      radar: {
        indicator,
        splitLine: { show: true }
      },
      series: [{
        name: model.name,
        type: 'radar',
        data: chartData
      }]
    }

    console.log(JSON.stringify(option, null, 2))

    this.chart.setOption(option)
  }
}
</script>

<style lang="scss" scoped>

</style>
